/*
 * Copyright:  2018 smarabbit studio.
 *
 * Licensed under the Confluent Community License; you may not use this file except in
 * compliance with the License.  You may obtain a copy of the License at
 *
 * http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software distributed under
 *  the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 *  either express or implied.  See the License for the specific language governing
 *  permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:    2020/7/11 上午8:59
 *
 */

package com.massyframework.beanskin.spring.beancontext.lazyinit;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.ResourceEntityResolver;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;

/**
 *
 */
public class LazyInitConfigurerXmlApplicationContext extends ClassPathXmlApplicationContext {

    private Boolean defaultLazyInit;

    /**
     * Create a new ClassPathXmlApplicationContext for bean-style configuration.
     *
     * @see #setConfigLocation
     * @see #setConfigLocations
     * @see #afterPropertiesSet()
     */
    public LazyInitConfigurerXmlApplicationContext() {
        this.defaultLazyInit = null;
    }

    public LazyInitConfigurerXmlApplicationContext(Boolean defaultLazyInit) {
        this.defaultLazyInit = defaultLazyInit;
    }

    /**
     * Loads the bean definitions via an XmlBeanDefinitionReader.
     *
     * @param beanFactory
     * @see XmlBeanDefinitionReader
     * @see #initBeanDefinitionReader
     * @see #loadBeanDefinitions
     */
    @Override
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
        // Create a new XmlBeanDefinitionReader for the given BeanFactory.
        LazyInitConfigurerXmlBeanDefinitionReader beanDefinitionReader = new LazyInitConfigurerXmlBeanDefinitionReader(beanFactory);
        beanDefinitionReader.setDocumentReaderClass(LazyInitConfigurerBeanDefinitionDocumentReader.class);
        beanDefinitionReader.setDefaultLayInit(this.defaultLazyInit);

        // Configure the bean definition reader with this context's
        // resource loading environment.
        beanDefinitionReader.setEnvironment(this.getEnvironment());
        beanDefinitionReader.setResourceLoader(this);
        beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

        // Allow a subclass to provide custom initialization of the reader,
        // then proceed with actually loading the bean definitions.
        initBeanDefinitionReader(beanDefinitionReader);
        loadBeanDefinitions(beanDefinitionReader);
    }
}
